/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.bm.setting;


import com.bm.config.server.IServerServices;
import com.bm.util.MessagePrinter;
import com.bm.util.PropertiesHandler;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.sql.DataSource;

/**
 *
 * @author IT
 */
public class ServerConfig {
    
    private static DataSource dataSourceLocal = null;
    private static Connection connectionLocal = null;
    private static PropertiesHandler properties;
    
    public ServerConfig(IServerServices serverServiceLocal) {
        try {
            properties = new PropertiesHandler();        
            dataSourceLocal = serverServiceLocal.getLocalDBConfig();
        } catch (IOException ex) {
            Logger.getLogger(ServerConfig.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public static Connection getConnection() {
        try {
            connectionLocal = dataSourceLocal.getConnection();
        } catch (SQLException e) {
            MessagePrinter.print("Koneksi ke server local terputus. Mencoba koneksi kembali dalam 10 detik.");
            try {
                Thread.sleep(10000);
            } catch (InterruptedException ex) {
                //Logger.getLogger(ServerConfig.class.getName()).log(Level.SEVERE, null, ex);
            }
            return getConnection();
        }
        return connectionLocal;        
    }
    
    public static String getDBName(){
        return properties.getServerDbName();
    }

    public static void close(Statement stmt) {
        if (null != stmt) {
            try {
                stmt.close();
            } catch (SQLException e) {
//				log.warn("Failed to close statement: " + e.getLocalizedMessage(), e);
            }
        }
    }
    
    public static void close(ResultSet rs) {
        if (null != rs) {
            try {
                rs.close();
            } catch (SQLException e) {
//				log.warn("Failed to close resultset: " + e.getLocalizedMessage(), e);
            }
        }
    }
    
    
     public static void close(Connection conn) {
        if (null != conn) {
            try {
                conn.close();
            } catch (SQLException e) {
//				log.warn("Failed to close resultset: " + e.getLocalizedMessage(), e);
            }
        }
    }
}
